package com.google.code.irouter.portal.client.dashboard.main.center.managers.relation.browser.monitor;

import java.util.ArrayList;
import java.util.List;

import com.google.code.irouter.portal.client.AppConstants;
import com.google.code.irouter.portal.client.dashboard.main.center.managers.relation.Browser;
import com.google.code.irouter.portal.client.dashboard.main.center.managers.relation.browser.monitor.relations.Command;
import com.google.code.irouter.portal.client.dashboard.main.north.menu.switcher.Solutions;
import com.google.code.irouter.portal.client.rpc.relation.RelationResult;
import com.google.code.irouter.portal.client.rpc.relation.RelationService;
import com.google.code.irouter.portal.client.rpc.relation.RelationServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Ext;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.event.GridRowListenerAdapter;

public final class Relations extends GridPanel {
	
	private static final AppConstants CONSTANTS = GWT.create(AppConstants.class);
	private final RelationServiceAsync relationService = GWT.create(RelationService.class);

	public Relations() {
		super();
		this.setId(Relations.class.getName());

		RecordDef recordDef = new RecordDef(
                new FieldDef[]{
                        new StringFieldDef("name"),  
                        new StringFieldDef("solution"),  
                        new IntegerFieldDef("collector"),  
                        new IntegerFieldDef("transponder"),
                        new StringFieldDef("key")
                }  
        );  
 
        MemoryProxy proxy = new MemoryProxy(new Object[0][0]);  
  
        ArrayReader reader = new ArrayReader(recordDef);  
        Store store = new Store(proxy, reader);  
        store.load();  
        this.setStore(store);  
  
  
        ColumnConfig[] columns = new ColumnConfig[]{
                new ColumnConfig(CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_monitor_relations_column_name(), "name", 160, true),  
                new ColumnConfig(CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_monitor_relations_column_solution(), "solution", 160, true),  
                new ColumnConfig(CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_monitor_relations_column_collector(), "collector", 160, true),  
                new ColumnConfig(CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_monitor_relations_column_transponder(), "transponder", 160, true)
        };  
  
        ColumnModel columnModel = new ColumnModel(columns);  
        this.setColumnModel(columnModel);  
        this.setStripeRows(true);  
   
        this.setTopToolbar(new Command()); 
        this.addGridRowListener(new GridRowListenerAdapter() {
        	public void onRowDblClick(GridPanel grid, int rowIndex, EventObject e) {
        		String id = getStore().getAt(rowIndex).getAsString("key");
        		String name = getStore().getAt(rowIndex).getAsString("name");
        		((Browser) Ext.getCmp(Browser.class.getName())).load(id, name);
            }
        });
        this.addListener(new RelationsListener());
        this.show();
	}
	
	public void remove() {
		getEl().mask(CONSTANTS.com_google_code_irouter_portal_client_common_processing(), true);
		Record[] records = getSelectionModel().getSelections();
		if(records.length > 0) {
			final List<String> idList = new ArrayList<String>();
			for(Record record : records) {
				idList.add(record.getAsString("key"));				
			}		
			relationService.remove(
					idList.toArray(new String[0]), 
					new AsyncCallback<Boolean>() {
						public void onFailure(Throwable caught) {
						// TODO
							getEl().unmask();
						}
		
						public void onSuccess(Boolean result) {
							refresh();
							getEl().unmask();
						}
					}
				);
		} else {
			getEl().unmask();
		}
	}
	
	public void reset() {
		RecordDef recordDef = new RecordDef(
                new FieldDef[]{
                        new StringFieldDef("name"),  
                        new StringFieldDef("solution"),  
                        new IntegerFieldDef("collector"),  
                        new IntegerFieldDef("transponder"),
                        new StringFieldDef("key")
                }  
        );  
 
        MemoryProxy proxy = new MemoryProxy(new Object[0][0]);  
  
        ArrayReader reader = new ArrayReader(recordDef);  
        Store store = new Store(proxy, reader);  
        store.load();  
        reconfigure(store, getColumnModel());
	}
	
	public void refresh() {
		getEl().mask(CONSTANTS.com_google_code_irouter_portal_client_common_processing(), true);
		String solutionId = "";
		String cookieId = Cookies.getCookie(Solutions.COOKIE_SOLUTION);
		if(cookieId != null)
			if(cookieId.trim().length() > 0)
				solutionId = cookieId;
		
		relationService.load(
				solutionId,
				new AsyncCallback<List<RelationResult>>() {
					public void onFailure(Throwable caught) {
					// TODO
						reset();
						getEl().unmask();
					}

					public void onSuccess(List<RelationResult> relationResultList) {
						if(relationResultList != null) {
							Object[][] relationArray = new Object[relationResultList.size()][5];
							int index = 0;
							for (RelationResult relationResult : relationResultList) {
								Object[] relationItem = new Object[5];
								relationItem[0] = relationResult.getName();
								relationItem[1] = relationResult.getSolutionName();
								relationItem[2] = relationResult.getCollector();
								relationItem[3] = relationResult.getTransponder();
								relationItem[4] = relationResult.getId();
								relationArray[index] = relationItem;
								index++;
							}
							
							RecordDef recordDef = new RecordDef(
					                new FieldDef[]{
					                        new StringFieldDef("name"),  
					                        new StringFieldDef("solution"),  
					                        new IntegerFieldDef("collector"),  
					                        new IntegerFieldDef("transponder"),
					                        new StringFieldDef("key")
					                }  
					        );  
					 
					        MemoryProxy proxy = new MemoryProxy(relationArray);  
					  
					        ArrayReader reader = new ArrayReader(recordDef);  
					        Store store = new Store(proxy, reader);  
					        store.load();  
	
							reconfigure(store, getColumnModel());							
						} else {
							reset();
						}
						getEl().unmask();
					}
				}
		);
	}

}
